
Ext.onReady(function(){
    Ext.QuickTips.init();
    Ext.BLANK_IMAGE_URL = 'ext3.2/resources/images/default/s.gif';
    var gridTitle = '展馆管理';
    var findall = "corpPavilion_all.do";
    var getNewIdUrl = "corpPavilion_newId.do";
    var addMsg = 'corpPavilion_add.do';
    var deleteMsg = 'corpPavilion_delete.do';
    var modifyMsg = 'corpPavilion_modify.do';
    
    var renderTo = 'pavilionmgr_grid';
    var seqValue = "corp_pavilion_seq"; //序列号名称
    var identityName = "id"; //主键名称
    var pageSize = 18;
    var gridHeight = 500;
    //id,name,keyword,imgsmallPath,imgPath," +
    //"xWidth,yHeight,zZoom,url,imgWidth," +
    //"imgHeight,parentId,imgFull,imgUp,imgMight
    var sm = new Ext.grid.CheckboxSelectionModel();
   var cm = new Ext.grid.ColumnModel([sm, {
        header: "编号",
        width: 100,
        dataIndex: 'id'
    }, {
        header: "展馆名",
        width: 100,
        sortable: true,
        dataIndex: 'name',
        editor: {
            xtype: 'textfield'
        }
    }, {
        header: "关键字",
        width: 100,
        dataIndex: 'keyword',
        editor: {
            xtype: 'textfield'
        }
    }, {
        header: "小图路径",
        width: 100,
        dataIndex: 'imgsmallPath',
        editor: {
            xtype: 'textfield'
        }
    }, {
        header: "大图路径",
        width: 100,
        dataIndex: 'imgPath',
        editor: {
            xtype: 'textfield'
        }
    }, {
        header: "位置编号",
        width: 100,
        dataIndex: 'roomNumber',
        editor: {
            xtype: 'textfield'
        }
    }, {
        header: "元件名称",
        width: 100,
        dataIndex: 'posName',
        editor: {
            xtype: 'textfield'
        }
    }, {
        header: "是否特装",
        width: 100,
        dataIndex: 'isSpecial',
        editor: {
            xtype: 'textfield'
        }
    }, {
        header: "父ID",
        width: 100,
        dataIndex: 'parentId',
        editor: {
            xtype: 'textfield'
        }
    }]);
    
    var Dict = Ext.data.Record.create([{
        name: 'id',
        type: 'int'
    }, {
        name: 'name',
        type: 'String'
    }, {
        name: 'keyword',
        type: 'string'
    }, {
        name: 'imgsmallpath',
        type: 'string'
    }, {
        name: 'imgPath',
        type: 'string'
    }, {
        name: 'parentId',
        type: 'int'
    }, {
        name: 'roomNumber',
        type: 'int'
    }, {
        name: 'posName',
        type: 'string'
    }, {
        name: 'isSpecial',
        type: 'int'
    }]);
    
    var reader = new Ext.data.JsonReader({
        root: 'rows', //rows : 为服务器端传送过来的记录数值对象
        totalProperty: 'total' //results 为服务器端json传送过来的记录的行数, count(*)运算
    }, ['id', 'name', 'keyword', 'imgsmallPath', 'imgPath', 'parentId', 'roomNumber', 'posName', 'isSpecial']);
    
    var saveHandler = function(e){
        var conn = new Ext.data.Connection();
        conn.request({
            url: modifyMsg,
            params: {
               'corpPavilion.id': e.record.get("id"),
                'corpPavilion.name': e.record.get("name"),
                'corpPavilion.keyword': e.record.get("keyword"),
                'corpPavilion.imgsmallPath': e.record.get("imgsmallPath"),
                'corpPavilion.imgPath': e.record.get("imgPath"),
                'corpPavilion.parentId': e.record.get("parentId"),
                'corpPavilion.roomNumber': e.record.get("roomNumber"),
                'corpPavilion.posName': e.record.get("posName"),
                'corpPavilion.isSpecial': e.record.get("isSpecial")
            },
            success: function(resp, opt){
            },
            failure: function(resp, opt){
                Ext.Msg.alert('Error', '修改失败！');
            }
        });
    }
    //add handle to deal with add action
    var addHandler = function(e){
        var newId;
        var conn = new Ext.data.Connection();
        conn.request({
            url: getNewIdUrl,
            params: {
                seqName: seqValue
            },
            success: function(resp, opt){
                newId = Ext.util.JSON.decode(resp.responseText).newId;
                openCreateWin(newId);
            },
            failure: function(resp, opt){
                Ext.Msg.alert('Error', '获取新id失败');
            }
        })
        
    };
    
    // add handler
    
    var openCreateWin = function(newId){
        var win;
        var f = new Ext.form.FormPanel({
            title: "添加信息",
            height: 520,
            autoWidth: true,
            labelWidth: 75,
            labelAlign: "center",
            frame: true,
            defaultType: 'textfield',
            defaults: {
                width: 300
            },
            buttonAlign: 'center',
            items: [{
                xtype: 'tabpanel',
                plain: true,
                activeTab: 0,
                height: 450,
                autoWidth: true,
                deferredRender: false,
                defaults: {
                    bodyStyle: 'padding:10px'
                },
                items: [{
                    title: '基本信息',
                    layout: 'form',
                    defaults: {
                        width: 400
                    },
                    defaultType: 'textfield',
                    items: [{
                        fieldLabel: '编号',
                        name: 'corpPavilion.id',
                        value: newId,
                        readOnly: true
                    }, {
                        fieldLabel: "展馆名",
                        name: 'corpPavilion.name'
                    }, {
                        fieldLabel: "关键字",
                        name: 'corpPavilion.keyword'
                    }, {
                        fieldLabel: "小图路径",
                        name: 'corpPavilion.imgsmallPath'
                    }, {
                        fieldLabel: "大图路径",
                        name: 'corpPavilion.imgPath'
                    }, new Ext.form.NumberField({
                        fieldLabel: "位置编号",
                        name: 'corpPavilion.roomNumber'
                    }), {
                        xtype: 'radiogroup',
                        fieldLabel: '是否特装',
                        items: [{
                            boxLabel: '是',
                            name: 'corpPavilion.isSpecial',
                            checked: true,
                            inputValue: 1
                        }, {
                            boxLabel: '否',
                            name: 'corpPavilion.isSpecial',
                            inputValue: 0
                        }]
                    }, {
                        fieldLabel: "元件名称",
                        name: 'corpPavilion.posName'
                    }, {
                        fieldLabel: "父ID",
                        name: 'corpPavilion.parentId'
                    }]
                }]
            }],
            
            buttons: [{
                text: "提交",
                handler: s
            }, {
                text: "重置",
                handler: function(){
                    f.form.reset();
                }
            }]
        });
        
        function s(){
            f.form.submit({
                waitTitle: "请稍候",
                waitMsg: "正在提交表单数据，请稍候.......",
                url: addMsg,
                success: function(action, form){
                    Ext.MessageBox.alert('提示信息', '数据已经成功提交！', function close(){
                        win.close();
                        location.replace(location.href);
                    });
                },
                failure: function(f, a){
                    Ext.MessageBox.alert('提示信息', "数据添加失败！");
                }
            });
            
        }
        
        if (!win) {
            win = new Ext.Window({
                title: '信息录入',
                width: 700,
                height: 570,
                x: 100,
                y: 50,
                closeAction: 'close',
                plain: true,
                modal: true,
                items: f
            });
        }
        win.show();
        
    };
    
    
    // 更新表单
    var updateFormHandler = function(){
        editor.stopEditing();
        var s = grid.getSelectionModel().getSelected();
        if (!s) 
            return false;
        var win;
        var updateForm = new Ext.form.FormPanel({
            title: "添加信息",
            height: 520,
            autoWidth: true,
            labelWidth: 75,
            labelAlign: "center",
            frame: true,
            defaultType: 'textfield',
            defaults: {
                width: 300
            },
            buttonAlign: 'center',
            items: [{
                xtype: 'tabpanel',
                plain: true,
                activeTab: 0,
                height: 460,
                autoWidth: true,
                deferredRender: false,
                defaults: {
                    bodyStyle: 'padding:10px'
                },
                items: [{
                    title: '基本信息',
                    layout: 'form',
                    defaults: {
                        width: 400
                    },
                    defaultType: 'textfield',
                    items: [{
                        fieldLabel: '编号',
                        name: 'corpPavilion.id',
                        value: s.get("id"),
                        readOnly: true
                    }, {
                        fieldLabel: "展馆名",
                        name: 'corpPavilion.name',
                        value: s.get("name")
                    }, {
                        fieldLabel: "关键字",
                        name: 'corpPavilion.keyword',
                        value: s.get("keyword")
                    }, {
                        fieldLabel: "小图路径",
                        name: 'corpPavilion.imgsmallPath',
                        value: s.get("imgsmallPath")
                    }, {
                        fieldLabel: "大图路径",
                        name: 'corpPavilion.imgPath',
                        value: s.get("imgPath")
                    }, new Ext.form.NumberField({
                        fieldLabel: "位置编号",
                        name: 'corpPavilion.roomNumber'
                    }), {
                        xtype: 'radiogroup',
                        fieldLabel: '是否特装',
                        items: [{
                            boxLabel: '有',
                            name: 'corpPavilion.isSpecial',
                            checked: s.get('isSpecial') == 1,
                            inputValue: 1
                        }, {
                            boxLabel: '无',
                            name: 'corpPavilion.isSpecial',
                            checked: s.get('isSpecial') == 0,
                            inputValue: 0
                        }]
                    }, {
                        fieldLabel: "元件名称",
                        name: 'corpPavilion.posName',
                        value: s.get("posName")
                    }, {
                        fieldLabel: "父ID",
                        name: 'corpPavilion.parentId',
                        value: s.get("parentId")
                    }]
                }]
            }],
            
            buttons: [{
                text: "提交",
                handler: updateSubmit
            }, {
                text: "重置",
                handler: function(){
                    updateForm.form.reset();
                }
            }]
        });
        
        function updateSubmit(){
            updateForm.form.submit({
                waitTitle: "请稍候",
                waitMsg: "正在提交表单数据，请稍候.......",
                url: modifyMsg,
                success: function(action, form){
                    Ext.MessageBox.alert('提示信息', '数据已经成功提交！', function close(){
                        win.close();
                        location.replace(location.href); // 重新载入数据
                    });
                },
                failure: function(f, a){
                    Ext.MessageBox.alert('提示信息', "数据添加失败！");
                }
            });
            
        }
        
        if (!win) {
            win = new Ext.Window({
                title: '信息更改',
                width: 700,
                height: 570,
                x: 100,
                y: 50,
                closeAction: 'close',
                plain: true,
                modal: true,
                items: updateForm
            });
        }
        win.show();
    }
    
    //-------------------------下面无需改动-----------------------------------------------------------
    
    var store = new Ext.data.Store({
        url: findall,
        reader: reader
    });
    store.load({
        params: {
            start: 0,
            limit: pageSize
        }
    });
    
    var editor = new Ext.ux.grid.RowEditor({
        saveText: '保存',
        cancelText: '取消',
        listeners: {
            afteredit: function(e){
                saveHandler(e);
            }
        }
    });
    
    var grid = new Ext.grid.GridPanel({
        renderTo: renderTo,
        frame: true,
        title: gridTitle,
        autoScroll: true,
        width: "auto",
        height: gridHeight,
        store: store,
        plugins: [editor],
        sm: sm,
        cm: cm,
        tbar: [{
            text: ' 增加 ',
            handler: function(e){
                addHandler(e)
            } //deal add
        }, {
            ref: '../removeBtn',
            text: ' 删除 ',
            disabled: true,
            handler: function(e){
                delHandler(e)
            } //处理删除函数 
        }, {
            ref: '../updateBtn',
            text: ' 修改 ',
            disabled: true,
            handler: function(){
                updateFormHandler();
            }
        }],
        viewConfig: {
            columnsText: "显示/隐藏列",
            sortAscText: "正序排列",
            sortDescText: "倒序排列"
        },
        bbar: new Ext.PagingToolbar({
            pageSize: pageSize,
            store: store,
            displayInfo: true,
            afterPageText: ' 共 {0} 页',
            beforePageText: '页 ',
            firstText: '第一页 ',
            prevText: '前一页',
            nextText: '下一页',
            lastText: '最后一页',
            refreshText: '刷新',
            displayMsg: '显示第 {0} 条到 {1} 条记录，一共 {2} 条',
            emptyMsg: "没有记录"
        })
    
    });
    
    grid.getSelectionModel().on('selectionchange', function(sm){
        grid.removeBtn.setDisabled(sm.getCount() < 1);
        grid.updateBtn.setDisabled(sm.getCount() != 1);
    });
    
    //删除的处理函数
    var delHandler = function(e){
        editor.stopEditing();
        var s = grid.getSelectionModel().getSelections();
        if (!s) 
            return false;
        Ext.Msg.show({
            title: '删除',
            buttons: Ext.MessageBox.YESNOCANCEL,
            msg: '确认删除？',
            fn: function(btn){
				if(btn == "no" || btn == "cancel") return;
                var ids = "";
                for (var i = 0; i < s.length; i++) { //要删除的记录ID拼串
                    ids = ids + s[i].get(identityName) + ",";
                }
                var conn = new Ext.data.Connection();
                conn.request({
                    url: deleteMsg,
                    params: {
                        delIds: ids
                    },
                    success: function(resp, opt){
                        for (var i = 0; i < s.length; i++) { //把store中相应的记录删掉
                            grid.getStore().remove(s[i]);
                        }
                        store.reload();
                    },
                    failure: function(resp, opt){
                        Ext.Msg.alert('错误', '删除记录失败！');
                    }
                });
            }
        });
    }
});
